<?php
namespace  App\Http\Controllers\Radius;
use  App\Http\Controllers\Controller;


use Illuminate\Http\Request;
use App\Common\ErrorDefine;


use DB;

use App\OnlieTeam;
use App\Teamqq;
use App\Rad_manage;


class  OnlineTeamController extends Controller
{
    /**
     *获取客服列表
     */
    public function getOnlineTeam()
    {
        $data = Teamqq::all();
        return self::ShowMessage($data);
    }


    /**
     * @param Request $request
     * 客服状态改变
     */
    public function getOnlineTeamUpdate(Request $request)
    {
        //  判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        if(!$request->has('id') && empty($request->has('id')))
        {
            self::ShowError(ErrorDefine::ONLINETEAM_ID_NOT_EXIST);
            return;
        }
        $id = $request->input('id');


        if(!$request->has('status') && empty($request->has('status')))
        {
            self::ShowError(ErrorDefine::ONLINETEAM_ID_NOT_STATUS);
            return;
        }
        $status = $request->input('status');

        $team = Teamqq::find($id);
        $team->status = $status;
        $team->save();

        return self::ShowMessage();
    }


    /**
     * 修改客服账号信息
     */
    public function onlineTeamUpdateUserInfo(Request $request)
    {

        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }


        //  判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        if(!$request->has('id') && empty($request->has('id')))
        {
            self::ShowError(ErrorDefine::ONLINETEAM_ID_NOT_EXIST);
            return;
        }
        $id = $request->input('id');

        if(!$request->has('username') && empty($request->has('username')))
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }

        $username = $request->input('username');

        if(!$request->has('qq') && empty($request->has('qq')))
        {
            self::ShowError(ErrorDefine::QQ_NOT_EXIST);
            return;
        }

        $qq = $request->input('qq');


        $team  = Teamqq::find($id);

        $team->username = $username;
        $team->qq = $qq;
        $team->save();

        return self::ShowMessage();

    }



    /**
     * @param Request $request
     * 删除客服信息
     */
    public function onlineTeamDeleteUserInfo(Request $request)
    {

        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }


        $where = [];
        //  判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        if(!$request->has('id') && empty($request->has('id')))
        {
            self::ShowError(ErrorDefine::ONLINETEAM_ID_NOT_EXIST);
            return;
        }
        $where['id'] = $request->input('id');

        if(!$request->has('username') && empty($request->has('username')))
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }

        $where['username'] = $request->input('username');

        if(!$request->has('qq') && empty($request->has('qq')))
        {
            self::ShowError(ErrorDefine::QQ_NOT_EXIST);
            return;
        }

        $where['qq'] = $request->input('qq');


        $ret = Teamqq::where($where)->delete();

        return self::ShowMessage();

    }

    
    /**
     * @param Request $request
     * 添加客服
     */
    public function onlineTeamAdd(Request $request)
    {

        $where = [];
        //  判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        if(!$request->has('username') && empty($request->has('username')))
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }

        $where['username'] = $request->input('username');

        if(!$request->has('qq') && empty($request->has('qq')))
        {
            self::ShowError(ErrorDefine::QQ_NOT_EXIST);
            return;
        }

        $where['qq'] = $request->input('qq');


        $id = Teamqq::insertGetId($where);

        if($id)
        {
            return self::ShowMessage();
        }else{
            self::ShowError(ErrorDefine::DATABASE_ERROR);
            return;
        }


    }


    /**
     * 获取客服数据列表
     */
    public function getOnlineTeamDataList(Request $request)
    {


        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }

        $end_date = date('Y-m-d H:i:s',time());
        $start_date = date('Y-m-d',time());

        if($request->has('end_date'))
        {
            $end_date = $request->input('end_date');
        }


        if($request->has('start_date'))
        {
            $start_date = $request->input('start_date');
        }

        $team = Teamqq::all()->toArray();

        foreach($team as &$value)
        {

            $count = OnlieTeam::where('qq',$value['qq'])->where('bargain',1)->where('audit',2)->where('created_at','>',$start_date)->where('created_at','<',$end_date)->where('price','>','1')->count();

            $value['count'] = $count;


            $value['no_audit'] = OnlieTeam::where('qq',$value['qq'])->where('created_at','>',$start_date)->where('created_at','<',$end_date)->where('audit',3)->count();//   1:未审核   2：已审核   3：待审核

            $value['click_num'] = OnlieTeam::where('qq',$value['qq'])->where('created_at','>',$start_date)->where('created_at','<',$end_date)->count();            //   1:未审核   2：已审核   3：待审核

            $time =  OnlieTeam::where('qq',$value['qq'])->orderBy('created_at','desc')->first();
            if($time)
            {
                $value['login_time'] = $time->created_at;
            }else{
                $value['login_time'] = '';
            }
        }
        return self::ShowMessage($team);

    }

    /**
     * @param Request $request
     * 获取用户客服互动列表
     */
    public function getOnlineTeamUserInfoDataList(Request $request)
    {


        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }

        $token = $request->input('token');
        $user = self::getTokenById($token);
        if(!$user)
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }
        $level= $user[0]['level'];

        $page_no = 0;
        $page_size = 50;
        $username = '';
        $end_date = date('Y-m-d H:i:s',time());
        $start_date = '1970-01-01 08:00:00';

        $audit = ['1','2','3'];
        if($request->input('page_no'))
        {
            $page_no  = $request->input('page_no');
            if($page_no){
                $page_no = $page_no - 1;
                if(is_numeric($page_no)){
                    if($page_no<0){
                        $page_no = 0;
                    }
                }
            }
        }

        if($request->input('page_size'))
        {
            $page_size = $request->input('page_size');
            if($page_size){
                if($page_size <=0 ){
                    $page_size =  50;
                }
            }
        }


        //  判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        if(!$request->has('qq') && empty($request->has('qq')))
        {
            self::ShowError(ErrorDefine::QQ_NOT_EXIST);
            return;
        }
        $qq = $request->input('qq');

        if($request->has('start_date'))
        {
            $start_date  = $request->input('start_date');
        }

        if($request->has('end_date'))
        {
            $end_date  = $request->input('end_date');
        }

        if($request->has('username'))
        {
            $username  = $request->input('username');
        }
        $sql="";
        if($request->has('audit'))
        {
            $audit  = $request->input('audit');
            switch($audit)
            {
                case 1: $audit=['1'];break;     //   未审核
                case 2: $audit=['2'];break;     //   已审核
                case 3: $audit=['3'];break;     //   待审核
                case 4: $audit = ['1','2','3'];break;     //   待审核

            }
        }

        //  审核数组
        $ret = OnlieTeam::whereIn('audit',$audit)->where('qq',$qq)->where('created_at','>',"{$start_date}")->where('created_at','<',"{$end_date}")
            ->where('name','like','%'.$username.'%')->offset($page_size*$page_no)->limit($page_size)->orderBY('created_at','desc')->get();


        $audit_count = OnlieTeam::whereIn('audit',$audit)->where('qq',$qq)->where('created_at','>',"{$start_date}")->where('created_at','<',"{$end_date}")
            ->where('name','like','%'.$username.'%')->count();

        $total = ceil($audit_count/$page_size);

        //  金额
        $money = OnlieTeam::where('price','>','0')->where('qq',$qq)->where('audit','2')->where('created_at','>',"{$start_date}")->where('created_at','<',"{$end_date}")
            ->where('name','like','%'.$username.'%')->sum('price');

        // 点击总数量
        $total_count = OnlieTeam::where('qq',$qq)->where('created_at','>',"{$start_date}")->where('created_at','<',"{$end_date}")
            ->where('name','like','%'.$username.'%')->count();

        //  成交数
        $bargain_number = OnlieTeam::where('qq',$qq)->where('bargain',1)->where('audit','2')->where('price','>','1')->where('created_at','>',"{$start_date}")->where('created_at','<',"{$end_date}")
            ->where('name','like','%'.$username.'%')->count();

        //IP 量

        $ip_num = OnlieTeam::where('qq',$qq)->where('created_at','>',"{$start_date}")->where('ip','!=','')->where('created_at','<',"{$end_date}")
            ->where('name','like','%'.$username.'%')->distinct()->count('ip');

        $turnover_ratio = 0;
        if($total_count > 0)
        {
            $turnover_ratio = round($bargain_number/$total_count,2) * 100;
        }

        foreach($ret as &$value)
        {
            switch($value->audit)
            {
                case 1: $value->audit_name = '未审核';break;
                case 2: $value->audit_name = '已审核';break;
                case 3: $value->audit_name = '待审核';break;
            }
        }

        $data = array(
            'num'=>$bargain_number,
            'money'=>$money,
            'ip'=>$ip_num,
            'turnover_ratio'=>$turnover_ratio,
            'count'=>$audit_count,
            'total_count'=>$total_count,
            'total'=>$total,
            'list'=>$ret
        );

        return self::ShowMessage($data);
    }


    /**
     * @param Request $request
     * 管理员提交审核
     */
    public function doSubmitAudit(Request $request)
    {
        //  判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        if(!$request->has('id') && empty($request->has('id')))
        {
            self::ShowError(ErrorDefine::ACCOUNT_ID_NOT_EXIST);
            return;
        }

        $id = $request->input('id');

        $id = explode(',',$id);

        $ret = OnlieTeam::whereIn('id',$id)->update(['audit'=>2]);

        return self::ShowMessage();

    }

    /**
     * 客服提交审核
     */
    public function doAddAudit(Request $request)
    {
        //  判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        if(!$request->has('id') && empty($request->has('id')))
        {
            self::ShowError(ErrorDefine::ACCOUNT_ID_NOT_EXIST);
            return;
        }

        $where = [];
        $params = [];
        if(!empty($request->input('name')))
        {
            $params['name'] = $request->input('name');
        }

        if(!empty($request->input('bargain')))
        {
            $params['bargain'] = $request->input('bargain');
        }

        $params['audit'] = 3;           //  1 未审核   2：已审核    3：待审核


        if(!empty($request->input('price')))
        {
            $params['price'] = $request->input('price');
        }

        if(!empty($request->input('qq')))
        {
            $where['qq'] = $request->input('qq');
        }


        if(!empty($request->input('created_at')))
        {
            $where['created_at'] = $request->input('created_at');
        }


        if(!empty($request->input('id')))
        {
            $where['id'] = $request->input('id');
        }


        $ret = OnlieTeam::where($where)->update($params);

        if($ret)
        {
            return self::ShowMessage();
        }else{
            self::ShowError(ErrorDefine::DATABASE_ERROR);
            return;
        }


    }

    /**
     * 删除客服信息数据
     */
    public function doAuditDelete(Request $request)
    {
        $where = [];
        //  判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        if(!$request->has('id') && empty($request->has('id')))
        {
            self::ShowError(ErrorDefine::ACCOUNT_ID_NOT_EXIST);
            return;
        }

        $where['id'] = $request->input('id');

        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }

        $token = $request->input('token');
        $user = self::getTokenById($token);
        if(!$user)
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }

        if(!$request->has('qq') && empty($request->has('qq')))
        {
            self::ShowError(ErrorDefine::QQ_NOT_EXIST);
            return;
        }

        $where['qq'] = $request->input('qq');


        if(!$request->has('created_at') && empty($request->has('created_at')))
        {
            self::ShowError(ErrorDefine::DATE_TYPE_NOT_EXIST);
            return;
        }


        $where['qq'] = $request->input('qq');


        $ret = OnlieTeam::where($where)->delete();

        if($ret)
        {
            return self::ShowMessage();
        }else{
            self::ShowError(ErrorDefine::DATABASE_ERROR);
            return;
        }


    }




    static function getTokenById($token)
    {
        $user = Rad_manage::where('token',$token)->get()->toArray();
        return $user;
    }


}